import store from '@/store/index.js'
import {
	clearChatGpt
} from '@/services/chat.js'
/**
 * 防抖
 * @param fn
 * @param wait
 * @returns {Function}
 * @constructor
 */
export function debounce(fn, wait = 500) {
	var timer; //计时器
	return function() {
		//----需要防抖的方法（fn）的参数----
		var args = arguments; //fn方法对象（数组形式）
		var that = this;
		//------------------
		clearTimeout(timer) //清除上次请求计时
		timer = setTimeout(() => { //计算请求时间，大于0.5s则发送请求
			fn.apply(that, args) //接受数组形式参数
		}, wait);
	}
}

export function throttle(fn, wait = 1000) {
	let timer = null
	// let timer// 计时器
	return function() {
		// ----需要防抖的方法（fn）的参数----
		var args = arguments // fn方法对象（数组形式）
		var that = this
		// ------------------
		if (timer) {
			return
		}
		timer = setTimeout(() => {
			// 计算请求时间，大于0.5s则发送请求
			fn.apply(that, args) // 接受数组形式参数
			timer = 0
		}, wait)
	}
}


export const validatePhone = (data) => {
	return /^(?:(?:\+|00)86)?1\d{10}$/.test(data)
}

export const validateEmail = (data) => {
	return /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(data)
}
//分享获取

export const isEmojiCharacter = (substring) => {
	for (var i = 0; i < substring.length; i++) {
		var hs = substring.charCodeAt(i)
		if (hs >= 0xd800 && hs <= 0xdbff) {
			if (substring.length > 1) {
				var ls = substring.charCodeAt(i + 1)
				var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000
				if (uc >= 0x1d000 && uc <= 0x1f77f) {
					return true
				}
			}
		} else if (substring.length > 1) {
			var a = substring.charCodeAt(i + 1)
			if (a === 0x20e3) {
				return true
			}
		} else {
			if (hs >= 0x2100 && hs <= 0x27ff) {
				return true
			} else if (hs >= 0x2B05 && hs <= 0x2b07) {
				return true
			} else if (hs >= 0x2934 && hs <= 0x2935) {
				return true
			} else if (hs >= 0x3297 && hs <= 0x3299) {
				return true
			} else if (hs === 0xa9 || hs === 0xae || hs === 0x303d || hs === 0x3030 ||
				hs === 0x2b55 || hs === 0x2b1c || hs === 0x2b1b ||
				hs === 0x2b50) {
				return true
			}
		}
	}
}

export const GetQueryString = (url, name) => {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = url.split('?')[1].match(reg); //获取url中"?"符后的字符串并正则匹配
	var context = "";
	if (r != null)
		context = r[2];
	reg = null;
	r = null;
	return context == null || context == "" || context == "undefined" ? "" : context;
}



export const deepClone = (obj, map = new WeakMap()) => {

	if (obj == null) return obj;

	if (obj instanceof Date) return new Date(obj);

	if (obj instanceof RegExp) return new RegExp(obj);

	if (typeof obj !== "object") return obj;

	if (map.get(obj)) return map.get(obj);

	let cloneObj = new obj.constructor();

	map.set(obj, cloneObj);

	for (let key in obj) {

		if (obj.hasOwnProperty(key)) {

			cloneObj[key] = deepClone(obj[key], map);

		}

	}

	return cloneObj;

};


export const replaceAllData = (data, match, replace) => {
	if (typeof String.prototype.replaceAll === "undefined") {
		return data.replace(new RegExp(match, 'gi'), () => replace);
	} else {
		return data.replaceAll(match, replace)
	}

}
// 判断的是否是JSON字符串
export const isJsonStr = (str) => {
	if (typeof str == 'string') {
		try {
			var obj = JSON.parse(str);
			// 等于这个条件说明就是JSON字符串 会返回true
			if (typeof obj == 'object' && obj) {
				return true;
			} else {
				//不是就返回false
				return false;
			}
		} catch (e) {
			return false;
		}
	}
	return false;
}

let isFirst = true

export const initChatGPT = async () => {
	if (isFirst) {
		isFirst = false
		clearChatGPTMsg()
	}
}

/**
 * 清空chatGpt 缓存
 */
export const clearChatGPTMsg = async () => {
	var appInstance = getApp();
	appInstance.globalData.gptChatList = []
	if (store.state.token) {
		const data = await clearChatGpt()
	}
}


// 文本 精度 (默认最小值为0)
export function numInput(num, precision, Limit) {
	if (precision === 0) {
		// 输入纯数字
		num = num.replace(/[^\d]/g, '')
		if (String(num)[1] === '0') {
			num = Number(num)
		}
		return JudgeSize(num, Limit)
	} else {
		num = num.replace(/[^\d.]/g, '')
		if (String(num)[0] === '0' && String(num)[1] !== '.') {
			num = Number(num)
		} else if (String(num)[0] === '.') {
			num = null
		} else {
			if (num.indexOf('.') != num.lastIndexOf('.')) {
				num = String(num).substring(0, num.lastIndexOf('.'))
			}
		}
		if (String(num).indexOf('.') !== -1) {
			num = String(num).substring(0, num.indexOf('.') + precision + 1)
		}
		return JudgeSize(num, Limit)
	}
}

export function JudgeSize(num, Limit) {
	console.log(num, Limit, num.length);
	// 判断是否超出限制，超出的话删除最后一位数
	if (Limit !== undefined) {
		if (
			parseFloat(num) >= parseFloat(Limit)
		) {
			num = String(num)
			num = num.slice(0, -1)
			return JudgeSize(num, Limit)
		} else {
			return num
		}
	} else {
		return num
	}
}